import 'dart:async';

import 'package:enjoy_plus/utils/eventbus.dart';
import 'package:enjoy_plus/utils/http.dart';
import 'package:enjoy_plus/utils/toast.dart';
import 'package:enjoy_plus/utils/token.dart';
import 'package:flutter/material.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  //状态变量时间
  int _time = 0;
  //定义倒计时timer
  Timer? _timer;
//倒计时函数
  _countDownTime() {
//如果正在倒计时的话,就不再继续执行倒计时
    if (_time > 0) {
      return;
    }
    //还没有开启倒计时的话,点击开始倒计时
    setState(() {
      _time = 10; //倒计时10秒
    });
    //开启倒计时
    Timer.periodic(const Duration(seconds: 1), (timer) {
      _timer = timer;
      setState(() {
        _time--;
        //倒计时结束
        if (_time <= 0) {
          timer.cancel();
        }
      });
    });
  }

//获取验证码
  _getCode() async {
    if (_time > 0) {
      return;
    }
    //1.校验当前是否有手机号
    if (mobileController.text.isEmpty) {
      return ToastUtil.showInfo('请输入手机号');
    }
    //2.校验手机号格式是否正确(正则)
    if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(mobileController.text)) {
      return ToastUtil.showInfo('手机号格式不正确');
    }
    //3.调接口获取验证码

    final res =
        await http.get('/code', params: {'mobile': mobileController.text});
    // ignore: avoid_print
    //print(res['data']['code']);
    // codeController.text = res['data']['code'];
    //延迟两秒把验证码赋值
    Future.delayed(const Duration(seconds: 2), () {
      codeController.text = res['data']['code'];
    });
    //4.倒计时
    _countDownTime();
  }

//实现登录
  _login() async {
    //1. 校验手机号
    if (mobileController.text.isEmpty) {
      return ToastUtil.showInfo('请输入手机号');
    }
    // 2. 验证手机号格式
    if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(mobileController.text)) {
      return ToastUtil.showInfo('手机号格式不正确');
    }
    //3. 校验验证码
    if (codeController.text.isEmpty) {
      return ToastUtil.showInfo('请输入验证码');
    }
    if (!RegExp(r'^\d{6}$').hasMatch(codeController.text) &&
        codeController.text.length != 6) {
      return ToastUtil.showInfo('请输入6位验证码');
    }
    //4. 调接口实现登录
    final res = await http.post('/login',
        {'mobile': mobileController.text, 'code': codeController.text});
    // print(res['data']['token']);
    //5.保存token 提示用户
    TokenManager().saveToken(res['data']['token']);
    ToastUtil.showSuccess('登录成功');
    //8.刷新用户信息
    eventBus.fire(RefreshEvent());
    //6.清除定时器    也可以在上面销毁控制器的时候销毁
    //_timer?.cancel();
    //7.返回上一页
    Navigator.pop(context);
  }

//创建手机号和验证码控制器
  final mobileController = TextEditingController();
  final codeController = TextEditingController();
  //销毁控制器
  @override
  void dispose() {
    super.dispose();
    mobileController.dispose();
    codeController.dispose();
    _timer?.cancel(); //清除登录后的定时器
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          title: const Text('登录'),
          backgroundColor: Colors.transparent,
          centerTitle: true,
        ),
        body: Container(
            padding: const EdgeInsets.all(20),
            child:
                Column(mainAxisAlignment: MainAxisAlignment.start, children: [
              const Row(
                children: [
                  Text('登录',
                      style:
                          TextStyle(fontSize: 25, fontWeight: FontWeight.bold))
                ],
              ),
              const SizedBox(height: 10),
              const Row(
                children: [
                  Text('加入享+, 让生活更轻松', style: TextStyle(fontSize: 15))
                ],
              ),
              const SizedBox(height: 30),
              Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Expanded(
                    child: TextField(
                      controller: mobileController,
                      decoration: const InputDecoration(
                        labelText: '手机号',
                        hintText: '请输入手机号',
                      ),
                    ),
                  ),
                  ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.white,
                      shadowColor: Colors.transparent,
                      foregroundColor: const Color.fromARGB(255, 85, 145, 175),
                      minimumSize: const Size(100, 50),
                    ),
                    onPressed: () {
                      //获取验证码
                      _getCode();
                    },
                    child:
                        _time > 0 ? Text('$_time秒后重新获取') : const Text('获取验证码'),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              TextField(
                controller: codeController,
                decoration: const InputDecoration(
                  labelText: '验证码',
                  hintText: '请输入6位验证码',
                ),
              ),
              const SizedBox(height: 8),
              const Row(children: [
                Text('未注册手机号经验证后将自动登录',
                    style: TextStyle(fontSize: 12, color: Colors.grey)),
              ]),
              const SizedBox(height: 50),
              Row(children: [
                Expanded(
                    child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: () {
                    _login();
                  },
                  child: const Text('登录',
                      style: TextStyle(color: Colors.white, fontSize: 20)),
                ))
              ])
            ])));
  }
}
